const router = require("koa-router")();
const ArticleModel = require("../../models/article");
const UserModel = require("../../models/users");
router.post("/api/articleCollect", async ctx => {
    let { id, collected } = ctx.request.body;
    console.log(collected);
    try {
        var data = await ArticleModel.findByIdAndUpdate({ _id: id }, { $set: { collected } });
        if (data) {
            var newData = await ArticleModel.find({_id:id})
            if(collected){
                await UserModel.updateOne({}, { $push: { collectsArticles: newData } });
                ctx.body = {
                    code: 200,
                    result: newData,
                    msg: "收藏成功！"
                }
            }else{
                await UserModel.updateOne({}, { $pull: { collectsArticles: {_id:id} } });
                ctx.body = {
                    code: 200,
                    result: data,
                    msg: "取消收藏"
                }
            }
        } else {
            ctx.body = {
                code: 400,
                msg: "请求的合集不存在"
            }
        }
    } catch (err) {
        ctx.body = {
            code: 400,
            msg: "请求参数不合法",
            request: "POST /api/doCollect"
        }
    }
})
module.exports = router;